import json
import random
import re

from django import http
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
from django_redis import get_redis_connection

from apps.users.response_code import RETCODE
from utils.email import Email
from . import constants
from libs.captcha.captcha import captcha


class ImageCodeView(View):
    """图片验证码的后端逻辑"""

    def get(self, request, uuid):
        # 获取图片验证码
        # 生成一张图片验证码
        _, text, image = captcha.generate_captcha()

        # 连接redis 变量名为code
        redis_conn = get_redis_connection('code')
        # 在redis中存入的名字 保存的时间 验证码内容
        redis_conn.setex('img_%s' % uuid, constants.IMAGE_CODE_REDIS_EXPIRES, text)

        # 将图片返回给前端
        return http.HttpResponse(image, content_type='jpeg/image')


#
# class SMSCodeView(View):
#     """发送短信验证码的后端逻辑"""
#
#     def get(self, request, mobile):
#         """
#         逻辑：
#         1.获取图片验证码
#         2.判断图片验证码是否正确
#         3.获取一个随机的短信验证码
#         4.返回
#         """
#         # 创建连接到redis的对象
#         redis_conn = get_redis_connection('code')
#         # 找到名为sms_mobile的变量
#         send_sms_flag = redis_conn.get('sms_%s' % mobile)
#         # 如果找到，说明刚发过短信
#         if send_sms_flag:
#             return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '发送短信过于频繁'})
#         # 接收参数
#         uuid = request.GET.get('uuid')
#         image_code = request.GET.get('image_code')
#
#         if not re.match(r'^1[3-9]\d{9}$', mobile):
#             return http.JsonResponse({'code': RETCODE.MOBILEERR, 'errmsg': '手机格式错误'})
#         redis_conn = get_redis_connection('code')
#         # 从redis中获取图片验证码(uuid相对应的)
#         image_code_server = redis_conn.get('img_%s' % uuid)
#         # 判断图片验证码是否过期
#         if image_code_server is None:
#             return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '验证码已过期'})
#
#         # 判断短信验证码的正确性
#         print('11111111111111111111', image_code_server)
#         print('22222222222222222222', image_code)
#         print(image_code_server.lower())
#         print(image_code.lower())
#         if image_code_server.decode().lower() != image_code.lower():
#             return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '验证码输入错误'})
#
#         # 删除redis中的图片验证码
#         redis_conn.delete('img_%s' % uuid)
#
#         # 随机生成一个短信验证码
#         sms_code = "%6d" % random.randint(0, 999999)
#         print('--------------------%s' % sms_code)
#
#         # 将短信验证码存入redis中
#         redis_conn.setex('sms_code%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
#
#         return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})


class SMSCodeView(View):
    """短信验证码"""

    def get(self, reqeust, mobile):
        """
        :param reqeust: 请求对象
        :param mobile: 手机号
        :return: JSON
        """
        # 接收参数
        image_code_client = reqeust.GET.get('image_code')
        uuid = reqeust.GET.get('uuid')

        # 校验参数
        if not all([image_code_client, uuid]):
            return http.JsonResponse({'code': RETCODE.NECESSARYPARAMERR, 'errmsg': '缺少必传参数'})

        # 创建连接到redis的对象
        redis_conn = get_redis_connection('code')
        # 提取图形验证码
        image_code_server = redis_conn.get('img_%s' % uuid)
        if image_code_server is None:
            # 图形验证码过期或者不存在
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图形验证码失效'})
        # 删除图形验证码，避免恶意测试图形验证码
        try:
            redis_conn.delete('img_%s' % uuid)
        except Exception as e:
            print(e)

        # 对比图形验证码
        image_code_server = image_code_server.decode()  # bytes转字符串
        if image_code_client.lower() != image_code_server.lower():  # 转小写后比较
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '输入图形验证码有误'})

        # 生成短信验证码：生成6位数验证码
        sms_code = '%06d' % random.randint(0, 999999)

        # 保存短信验证码
        redis_conn.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # 为了在测试期间减少短信发送，可以屏蔽发送短信功能，使用打印的方式来获取到真正的验证码值
        # 发送短信验证码
        # send_sms(mobile, sms_code)
        print(">>>>短信验证码>>>>>>", sms_code)

        # 响应结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '发送短信成功'})


class EmailView(View):
    """添加邮箱"""

    def put(self, request):
        """实现添加邮箱逻辑"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        email = json_dict.get('email')

        # 校验参数
        if not email:
            return http.HttpResponseBadRequest('缺少email参数')
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.HttpResponseBadRequest('参数email有误')

        # 赋值email字段
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '添加邮箱失败'})

        # 发送验证邮件
        ret = Email.send_email(request, email)
        print(">>>>>>>>发送邮件>>>>>>", ret)

        # 响应添加邮箱结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加邮箱成功'})


class VerifyEmailView(View):
    """验证邮箱"""

    def get(self, request):
        """实现邮箱验证逻辑"""
        # 接收参数
        token = request.GET.get('token')

        # 校验参数：判断token是否为空和过期，提取user
        if not token:
            return http.HttpResponseBadRequest('缺少token')

        # 验证邮箱url是否有效
        user = Email.verify_email(token)
        if not user:
            return http.HttpResponseBadRequest('无效的token')

        # 修改email_active的值为True
        try:
            user.email_active = True
            user.save()
        except Exception as e:
            return http.HttpResponseServerError('激活邮件失败')

        # 返回邮箱验证结果
        return redirect(reverse('users:user_center'))